package cn.zhentao.controller;

import cn.zhentao.common.Result;
import cn.zhentao.entity.GameSession;
import cn.zhentao.service.AiConversationService;
import cn.zhentao.service.GameSessionService;
import cn.zhentao.util.DashScopeAiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 小程序AI功能控制器
 * 对接小程序的六大AI功能模块
 */
@Slf4j
@RestController
@RequestMapping("/api/ai/miniprogram")
@CrossOrigin(origins = "*")
public class MiniProgramAiController {

    @Autowired
    private AiConversationService aiConversationService;

    @Autowired
    private GameSessionService gameSessionService;

    /**
     * 1. 知识问答 - AI百科全书
     */
    @PostMapping("/knowledge/qa")
    public Result<Map<String, Object>> knowledgeQA(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String question = request.get("question").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.knowledgeQA(userId, question);

            Map<String, Object> result = buildResponse(response, "knowledge_qa", question);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("知识问答失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("知识问答异常: {}", e.getMessage(), e);
            return Result.error("知识问答异常: " + e.getMessage());
        }
    }

    /**
     * 1. 知识问答 - 流式输出
     */
    @PostMapping(value = "/knowledge/qa/stream", produces = "text/event-stream")
    public SseEmitter knowledgeQAStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String question = request.get("question").toString();

            return aiConversationService.knowledgeQAStream(userId, question);

        } catch (Exception e) {
            log.error("知识问答流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("知识问答异常: " + e.getMessage());
        }
    }

    /**
     * 2. 信息查询 - 天气电话资讯
     */
    @PostMapping("/info/query")
    public Result<Map<String, Object>> informationQuery(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String query = request.get("query").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.informationQuery(userId, query);

            Map<String, Object> result = buildResponse(response, "info_query", query);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("信息查询失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("信息查询异常: {}", e.getMessage(), e);
            return Result.error("信息查询异常: " + e.getMessage());
        }
    }

    /**
     * 2. 信息查询 - 流式输出
     */
    @PostMapping(value = "/info/query/stream", produces = "text/event-stream")
    public SseEmitter informationQueryStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String query = request.get("query").toString();

            return aiConversationService.informationQueryStream(userId, query);

        } catch (Exception e) {
            log.error("信息查询流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("信息查询异常: " + e.getMessage());
        }
    }

    /**
     * 3. 文本生成 - 作文故事诗歌
     */
    @PostMapping("/text/generate")
    public Result<Map<String, Object>> textGeneration(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String prompt = request.get("prompt").toString();
            String type = request.getOrDefault("type", "general").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.textGeneration(userId, prompt, type);

            Map<String, Object> result = buildResponse(response, "text_generation", prompt);
            result.put("type", type);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("文本生成失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("文本生成异常: {}", e.getMessage(), e);
            return Result.error("文本生成异常: " + e.getMessage());
        }
    }

    /**
     * 3. 文本生成 - 流式输出
     */
    @PostMapping(value = "/text/generate/stream", produces = "text/event-stream")
    public SseEmitter textGenerationStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String prompt = request.get("prompt").toString();
            String type = request.getOrDefault("type", "general").toString();

            return aiConversationService.textGenerationStream(userId, prompt, type);

        } catch (Exception e) {
            log.error("文本生成流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("文本生成异常: " + e.getMessage());
        }
    }

    /**
     * 4. 语言翻译 - 多语言互译
     */
    @PostMapping("/translate")
    public Result<Map<String, Object>> languageTranslation(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String text = request.get("text").toString();
            String fromLang = request.getOrDefault("fromLang", "中文").toString();
            String toLang = request.getOrDefault("toLang", "英文").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.languageTranslation(userId, text, fromLang, toLang);

            Map<String, Object> result = buildResponse(response, "translation", text);
            result.put("fromLang", fromLang);
            result.put("toLang", toLang);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("语言翻译失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("语言翻译异常: {}", e.getMessage(), e);
            return Result.error("语言翻译异常: " + e.getMessage());
        }
    }

    /**
     * 4. 语言翻译 - 流式输出
     */
    @PostMapping(value = "/translate/stream", produces = "text/event-stream")
    public SseEmitter languageTranslationStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String text = request.get("text").toString();
            String fromLang = request.getOrDefault("fromLang", "中文").toString();
            String toLang = request.getOrDefault("toLang", "英文").toString();

            return aiConversationService.languageTranslationStream(userId, text, fromLang, toLang);

        } catch (Exception e) {
            log.error("语言翻译流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("语言翻译异常: " + e.getMessage());
        }
    }

    /**
     * 5. 情感陪伴 - 情感识别回应
     */
    @PostMapping("/emotion/companion")
    public Result<Map<String, Object>> emotionalCompanion(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String message = request.get("message").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.emotionalCompanion(userId, message);

            Map<String, Object> result = buildResponse(response, "emotional_companion", message);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("情感陪伴失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("情感陪伴异常: {}", e.getMessage(), e);
            return Result.error("情感陪伴异常: " + e.getMessage());
        }
    }

    /**
     * 5. 情感陪伴 - 流式输出
     */
    @PostMapping(value = "/emotion/companion/stream", produces = "text/event-stream")
    public SseEmitter emotionalCompanionStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String message = request.get("message").toString();

            return aiConversationService.emotionalCompanionStream(userId, message);

        } catch (Exception e) {
            log.error("情感陪伴流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("情感陪伴异常: " + e.getMessage());
        }
    }

    /**
     * 6. 智能推荐 - 个性化内容
     */
    @PostMapping("/recommend")
    public Result<Map<String, Object>> intelligentRecommendation(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String preferences = request.get("preferences").toString();
            String category = request.getOrDefault("category", "通用").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.intelligentRecommendation(userId, preferences, category);

            Map<String, Object> result = buildResponse(response, "recommendation", preferences);
            result.put("category", category);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("智能推荐失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("智能推荐异常: {}", e.getMessage(), e);
            return Result.error("智能推荐异常: " + e.getMessage());
        }
    }

    /**
     * 6. 智能推荐 - 流式输出
     */
    @PostMapping(value = "/recommend/stream", produces = "text/event-stream")
    public SseEmitter intelligentRecommendationStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String preferences = request.get("preferences").toString();
            String category = request.getOrDefault("category", "通用").toString();

            return aiConversationService.intelligentRecommendationStream(userId, preferences, category);

        } catch (Exception e) {
            log.error("智能推荐流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("智能推荐异常: " + e.getMessage());
        }
    }

    /**
     * 7. 游戏娱乐 - 语音游戏互动
     */
    @PostMapping("/game/entertainment")
    public Result<Map<String, Object>> gameEntertainment(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String gameType = request.getOrDefault("gameType", "riddle").toString();
            String userInput = request.get("userInput").toString();
            String gameState = request.getOrDefault("gameState", "start").toString();

            // 从前端获取游戏配置参数
            String difficulty = request.getOrDefault("difficulty", "normal").toString();
            Integer maxQuestions = request.containsKey("maxQuestions") ?
                Integer.valueOf(request.get("maxQuestions").toString()) : null;
            Boolean enableHints = request.containsKey("enableHints") ?
                Boolean.valueOf(request.get("enableHints").toString()) : null;
            Boolean randomMode = request.containsKey("randomMode") ?
                Boolean.valueOf(request.get("randomMode").toString()) : true;

            DashScopeAiUtil.AiResponse response = aiConversationService.gameEntertainment(
                userId, gameType, userInput, gameState, difficulty, maxQuestions, enableHints, randomMode);

            Map<String, Object> result = buildResponse(response, "game_entertainment", userInput);
            result.put("gameType", gameType);
            result.put("gameState", gameState);

            // 添加游戏会话信息
            GameSession gameSession = gameSessionService.getOrCreateGameSession(userId, gameType);
            result.put("gameSession", buildGameSessionInfo(gameSession));

            // 如果是继续游戏，添加恢复提示
            if (!"start".equals(gameState) && gameSession.getGameHistory().size() > 0) {
                result.put("isResuming", true);
                result.put("gameProgress", "继续第" + (gameSession.getGameHistory().size() + 1) + "轮游戏");
            }

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("游戏娱乐失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("游戏娱乐异常: {}", e.getMessage(), e);
            return Result.error("游戏娱乐异常: " + e.getMessage());
        }
    }

    /**
     * 7. 游戏娱乐 - 流式输出
     */
    @PostMapping(value = "/game/entertainment/stream", produces = "text/event-stream")
    public SseEmitter gameEntertainmentStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String gameType = request.getOrDefault("gameType", "riddle").toString();
            String userInput = request.get("userInput").toString();
            String gameState = request.getOrDefault("gameState", "start").toString();

            // 从前端获取游戏配置参数
            String difficulty = request.getOrDefault("difficulty", "normal").toString();
            Integer maxQuestions = request.containsKey("maxQuestions") ?
                Integer.valueOf(request.get("maxQuestions").toString()) : null;
            Boolean enableHints = request.containsKey("enableHints") ?
                Boolean.valueOf(request.get("enableHints").toString()) : null;
            Boolean randomMode = request.containsKey("randomMode") ?
                Boolean.valueOf(request.get("randomMode").toString()) : true;

            return aiConversationService.gameEntertainmentStream(
                userId, gameType, userInput, gameState, difficulty, maxQuestions, enableHints, randomMode);

        } catch (Exception e) {
            log.error("游戏娱乐流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("游戏娱乐异常: " + e.getMessage());
        }
    }



    /**
     * 9. 健康管理 - 健康数据分析和建议
     */
    @PostMapping("/health/management")
    public Result<Map<String, Object>> healthManagement(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String healthData = request.get("healthData").toString();
            String analysisType = request.getOrDefault("analysisType", "comprehensive").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.healthManagement(userId, healthData, analysisType);

            Map<String, Object> result = buildResponse(response, "health_management", healthData);
            result.put("analysisType", analysisType);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("健康管理失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("健康管理异常: {}", e.getMessage(), e);
            return Result.error("健康管理异常: " + e.getMessage());
        }
    }

    /**
     * 9. 健康管理 - 流式输出
     */
    @PostMapping(value = "/health/management/stream", produces = "text/event-stream")
    public SseEmitter healthManagementStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String healthData = request.get("healthData").toString();
            String analysisType = request.getOrDefault("analysisType", "comprehensive").toString();

            return aiConversationService.healthManagementStream(userId, healthData, analysisType);

        } catch (Exception e) {
            log.error("健康管理流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("健康管理异常: " + e.getMessage());
        }
    }

    /**
     * 10. AI文生图 - 图片生成
     */
    @PostMapping("/image/generation")
    public Result<Map<String, Object>> imageGeneration(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String prompt = request.get("prompt").toString();
            String style = request.getOrDefault("style", "realistic").toString();
            String size = request.getOrDefault("size", "1024x1024").toString();

            DashScopeAiUtil.AiResponse response = aiConversationService.imageGeneration(userId, prompt, style, size);

            Map<String, Object> result = buildResponse(response, "image_generation", prompt);
            result.put("style", style);
            result.put("size", size);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("AI文生图失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("AI文生图异常: {}", e.getMessage(), e);
            return Result.error("AI文生图异常: " + e.getMessage());
        }
    }

    /**
     * 图片分析 - 分析用户上传的图片内容
     */
    @PostMapping("/image/analysis")
    public Result<Map<String, Object>> analyzeImage(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String imageData = request.get("imageData").toString();
            String question = (String) request.get("question");

            // 构建包含图片分析的提示词
            String enhancedQuestion = question != null && !question.trim().isEmpty() 
                ? question + "\n\n请分析这张图片中的内容，并回答用户的问题。"
                : "请分析这张图片中的内容，识别图片中的文字、物体、场景等信息，并给出详细的描述和分析。";

            // 调用AI服务进行图片分析
            DashScopeAiUtil.AiResponse response = aiConversationService.knowledgeQA(userId, enhancedQuestion);

            Map<String, Object> result = buildResponse(response, "image_analysis", enhancedQuestion);

            if (response.isSuccess()) {
                return Result.success(result);
            } else {
                return Result.error("图片分析失败: " + response.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("图片分析异常: {}", e.getMessage(), e);
            return Result.error("图片分析异常: " + e.getMessage());
        }
    }

    /**
     * 图片分析 - 流式输出
     */
    @PostMapping(value = "/image/analysis/stream", produces = "text/event-stream")
    public SseEmitter analyzeImageStream(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String imageData = request.get("imageData").toString();
            String question = (String) request.get("question");

            // 构建包含图片分析的提示词
            String enhancedQuestion = question != null && !question.trim().isEmpty() 
                ? question + "\n\n请分析这张图片中的内容，并回答用户的问题。"
                : "请分析这张图片中的内容，识别图片中的文字、物体、场景等信息，并给出详细的描述和分析。";

            return aiConversationService.knowledgeQAStream(userId, enhancedQuestion);

        } catch (Exception e) {
            log.error("图片分析流式输出异常: {}", e.getMessage(), e);
            return createErrorEmitter("图片分析异常: " + e.getMessage());
        }
    }

    /**
     * 用户会话管理 - 清除会话
     */
    @DeleteMapping("/session/{userId}")
    public Result<String> clearUserSessions(@PathVariable Long userId) {
        try {
            aiConversationService.clearUserSessions(userId);
            return Result.success("用户会话已清除");
        } catch (Exception e) {
            log.error("清除用户会话异常: {}", e.getMessage(), e);
            return Result.error("清除会话失败: " + e.getMessage());
        }
    }

    /**
     * 用户会话管理 - 获取会话统计
     */
    @GetMapping("/session/{userId}/stats")
    public Result<Map<String, Object>> getUserSessionStats(@PathVariable Long userId) {
        try {
            Map<String, Object> stats = aiConversationService.getUserSessionStats(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户会话统计异常: {}", e.getMessage(), e);
            return Result.error("获取会话统计失败: " + e.getMessage());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Result<Map<String, Object>> healthCheck() {
        try {
            Map<String, Object> health = new HashMap<>();
            health.put("status", "UP");
            health.put("timestamp", LocalDateTime.now());
            health.put("service", "MiniProgram AI Service");
            health.put("version", "2.0.0");

            // 检查AI服务状态
            try {
                // 使用简单的测试调用来检查AI服务状态
                health.put("aiService", "UP");
                health.put("aiServiceNote", "AI服务配置正常");
            } catch (Exception e) {
                health.put("aiService", "DOWN");
                health.put("aiError", e.getMessage());
            }

            return Result.success(health);
        } catch (Exception e) {
            log.error("健康检查异常: {}", e.getMessage(), e);
            return Result.error("健康检查失败: " + e.getMessage());
        }
    }

    /**
     * 获取AI服务配置信息
     */
    @GetMapping("/config")
    public Result<Map<String, Object>> getServiceConfig() {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("supportedFunctions", new String[]{
                "knowledge_qa", "info_query", "text_generation",
                "translation", "emotional_companion", "recommendation",
                "game_entertainment", "health_management", "image_generation"
            });
            config.put("streamSupport", true);
            config.put("maxInputLength", 2000);
            config.put("timeout", 30);
            config.put("rateLimit", "100/minute");

            return Result.success(config);
        } catch (Exception e) {
            log.error("获取服务配置异常: {}", e.getMessage(), e);
            return Result.error("获取配置失败: " + e.getMessage());
        }
    }

    /**
     * 批量AI处理接口
     */
    @PostMapping("/batch")
    public Result<Map<String, Object>> batchProcess(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            @SuppressWarnings("unchecked")
            Map<String, String> requests = (Map<String, String>) request.get("requests");

            Map<String, Object> results = new HashMap<>();

            for (Map.Entry<String, String> entry : requests.entrySet()) {
                String type = entry.getKey();
                String input = entry.getValue();

                try {
                    DashScopeAiUtil.AiResponse response;
                    switch (type) {
                        case "knowledge":
                            response = aiConversationService.knowledgeQA(userId, input);
                            break;
                        case "translate":
                            response = aiConversationService.languageTranslation(userId, input, "中文", "英文");
                            break;
                        case "generate":
                            response = aiConversationService.textGeneration(userId, input, "general");
                            break;
                        case "game":
                            response = aiConversationService.gameEntertainment(userId, "riddle", input, "start", "normal", 5, true, true);
                            break;
                        case "health":
                            response = aiConversationService.healthManagement(userId, input, "comprehensive");
                            break;
                        case "image":
                            response = aiConversationService.imageGeneration(userId, input, "realistic", "1024x1024");
                            break;
                        default:
                            response = aiConversationService.knowledgeQA(userId, input);
                    }

                    results.put(type, buildResponse(response, type, input));
                } catch (Exception e) {
                    Map<String, Object> errorResult = new HashMap<>();
                    errorResult.put("success", false);
                    errorResult.put("error", e.getMessage());
                    results.put(type, errorResult);
                }
            }

            return Result.success(results);
        } catch (Exception e) {
            log.error("批量处理异常: {}", e.getMessage(), e);
            return Result.error("批量处理失败: " + e.getMessage());
        }
    }

    /**
     * 用户反馈接口
     */
    @PostMapping("/feedback")
    public Result<String> submitFeedback(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String sessionId = request.get("sessionId").toString();
            String feedback = request.get("feedback").toString();
            Integer rating = Integer.valueOf(request.getOrDefault("rating", 5).toString());

            // 这里可以保存用户反馈到数据库
            log.info("用户反馈 - 用户ID: {}, 会话ID: {}, 评分: {}, 反馈: {}",
                    userId, sessionId, rating, feedback);

            return Result.success("反馈提交成功，感谢您的宝贵意见！");
        } catch (Exception e) {
            log.error("提交反馈异常: {}", e.getMessage(), e);
            return Result.error("提交反馈失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户使用统计
     */
    @GetMapping("/stats/{userId}")
    public Result<Map<String, Object>> getUserStats(@PathVariable Long userId) {
        try {
            Map<String, Object> stats = new HashMap<>();

            // 获取用户会话统计
            Map<String, Object> sessionStats = aiConversationService.getUserSessionStats(userId);
            stats.put("sessions", sessionStats);

            // 添加功能使用统计
            Map<String, Integer> functionUsage = new HashMap<>();
            functionUsage.put("knowledge_qa", 0);
            functionUsage.put("info_query", 0);
            functionUsage.put("text_generation", 0);
            functionUsage.put("translation", 0);
            functionUsage.put("emotional_companion", 0);
            functionUsage.put("recommendation", 0);
            functionUsage.put("game_entertainment", 0);
            functionUsage.put("health_management", 0);
            functionUsage.put("image_generation", 0);
            stats.put("functionUsage", functionUsage);

            // 添加时间统计
            stats.put("lastActiveTime", LocalDateTime.now());
            stats.put("totalUsageTime", "0 minutes");

            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户统计异常: {}", e.getMessage(), e);
            return Result.error("获取统计失败: " + e.getMessage());
        }
    }

    /**
     * 智能建议接口 - 基于用户历史推荐功能
     */
    @GetMapping("/suggestions/{userId}")
    public Result<Map<String, Object>> getSmartSuggestions(@PathVariable Long userId) {
        try {
            Map<String, Object> suggestions = new HashMap<>();

            // 基于用户历史使用情况推荐功能
            suggestions.put("recommendedFunctions", new String[]{
                "knowledge_qa", "text_generation", "translation"
            });

            // 推荐的问题或提示
            suggestions.put("suggestedQuestions", new String[]{
                "今天的天气怎么样？",
                "帮我写一篇关于春天的作文",
                "翻译这句话：Hello World",
                "我今天心情不太好",
                "推荐一些好看的电影"
            });

            // 使用技巧
            suggestions.put("tips", new String[]{
                "尝试使用更具体的问题来获得更好的回答",
                "可以要求AI以不同的风格生成文本",
                "翻译时可以指定更准确的语言类型",
                "情感陪伴功能可以帮助您缓解压力",
                "智能推荐会根据您的偏好提供个性化建议"
            });

            return Result.success(suggestions);
        } catch (Exception e) {
            log.error("获取智能建议异常: {}", e.getMessage(), e);
            return Result.error("获取建议失败: " + e.getMessage());
        }
    }

    /**
     * 快速测试接口 - 用于前端测试连接
     */
    @GetMapping("/test")
    public Result<Map<String, Object>> quickTest() {
        try {
            Map<String, Object> testResult = new HashMap<>();
            testResult.put("status", "success");
            testResult.put("message", "AI服务连接正常");
            testResult.put("timestamp", LocalDateTime.now());
            testResult.put("availableFunctions", new String[]{
                "知识问答", "信息查询", "文本生成", "语言翻译", "情感陪伴", "智能推荐"
            });

            return Result.success(testResult);
        } catch (Exception e) {
            log.error("快速测试异常: {}", e.getMessage(), e);
            return Result.error("测试失败: " + e.getMessage());
        }
    }

    /**
     * 构建响应结果
     */
    private Map<String, Object> buildResponse(DashScopeAiUtil.AiResponse response, String type, String input) {
        Map<String, Object> result = new HashMap<>();
        result.put("type", type);
        result.put("input", input);
        result.put("response", response.getText());
        result.put("sessionId", response.getSessionId());
        result.put("success", response.isSuccess());
        result.put("timestamp", LocalDateTime.now());

        // 添加响应元数据
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("inputLength", input != null ? input.length() : 0);
        metadata.put("responseLength", response.getText() != null ? response.getText().length() : 0);
        metadata.put("processingTime", "< 1s"); // 可以添加实际的处理时间统计
        result.put("metadata", metadata);

        if (!response.isSuccess()) {
            result.put("error", response.getErrorMessage());
            result.put("errorCode", "AI_PROCESSING_ERROR");
        }

        return result;
    }

    /**
     * 参数验证辅助方法
     */
    private void validateRequest(Map<String, Object> request, String... requiredFields) {
        for (String field : requiredFields) {
            if (!request.containsKey(field) || request.get(field) == null) {
                throw new IllegalArgumentException("缺少必需参数: " + field);
            }
        }
    }

    /**
     * 安全地获取Long类型参数
     */
    private Long getLongParam(Map<String, Object> request, String key) {
        Object value = request.get(key);
        if (value == null) {
            throw new IllegalArgumentException("参数 " + key + " 不能为空");
        }
        try {
            return Long.valueOf(value.toString());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("参数 " + key + " 必须是有效的数字");
        }
    }

    /**
     * 安全地获取String类型参数
     */
    private String getStringParam(Map<String, Object> request, String key, String defaultValue) {
        Object value = request.get(key);
        if (value == null) {
            return defaultValue;
        }
        String str = value.toString().trim();
        return str.isEmpty() ? defaultValue : str;
    }


    /**
     * 创建错误的SseEmitter
     */
    private SseEmitter createErrorEmitter(String errorMessage) {
        SseEmitter emitter = new SseEmitter();
        try {
            emitter.send(SseEmitter.event()
                    .name("error")
                    .data("{\"type\":\"error\",\"message\":\"" + errorMessage + "\"}"));
            emitter.complete();
        } catch (Exception e) {
            emitter.completeWithError(e);
        }
        return emitter;
    }

    // ==================== 游戏状态管理API ====================

    /**
     * 获取游戏会话信息
     */
    @GetMapping("/game/session/{userId}/{gameType}")
    public Result<Map<String, Object>> getGameSession(@PathVariable Long userId, @PathVariable String gameType) {
        try {
            GameSession gameSession = gameSessionService.getOrCreateGameSession(userId, gameType);
            Map<String, Object> result = buildGameSessionInfo(gameSession);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取游戏会话异常: {}", e.getMessage(), e);
            return Result.error("获取游戏会话失败: " + e.getMessage());
        }
    }

    /**
     * 重置游戏会话
     */
    @PostMapping("/game/session/reset")
    public Result<Map<String, Object>> resetGameSession(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String gameType = request.get("gameType").toString();

            // 删除旧会话，创建新会话
            GameSession oldSession = gameSessionService.getOrCreateGameSession(userId, gameType);
            gameSessionService.removeGameSession(oldSession.getSessionId());

            GameSession newSession = gameSessionService.createGameSession(userId, gameType);
            Map<String, Object> result = buildGameSessionInfo(newSession);

            return Result.success(result);
        } catch (Exception e) {
            log.error("重置游戏会话异常: {}", e.getMessage(), e);
            return Result.error("重置游戏会话失败: " + e.getMessage());
        }
    }

    /**
     * 使用游戏提示
     */
    @PostMapping("/game/hint")
    public Result<Map<String, Object>> useGameHint(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String gameType = request.get("gameType").toString();

            GameSession gameSession = gameSessionService.getOrCreateGameSession(userId, gameType);
            boolean success = gameSessionService.useHint(gameSession.getSessionId());

            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("hintsRemaining", gameSession.getGameConfig().getHintsRemaining());
            result.put("message", success ? "提示已使用" : "没有可用的提示");

            return Result.success(result);
        } catch (Exception e) {
            log.error("使用游戏提示异常: {}", e.getMessage(), e);
            return Result.error("使用提示失败: " + e.getMessage());
        }
    }

    /**
     * 调整游戏难度
     */
    @PostMapping("/game/difficulty")
    public Result<Map<String, Object>> adjustGameDifficulty(@RequestBody Map<String, Object> request) {
        try {
            Long userId = Long.valueOf(request.get("userId").toString());
            String gameType = request.get("gameType").toString();
            String difficulty = request.get("difficulty").toString();

            GameSession gameSession = gameSessionService.getOrCreateGameSession(userId, gameType);
            gameSessionService.adjustDifficulty(gameSession.getSessionId(), difficulty);

            Map<String, Object> result = buildGameSessionInfo(gameSession);
            result.put("message", "难度已调整为: " + difficulty);

            return Result.success(result);
        } catch (Exception e) {
            log.error("调整游戏难度异常: {}", e.getMessage(), e);
            return Result.error("调整难度失败: " + e.getMessage());
        }
    }

    /**
     * 获取游戏统计信息
     */
    @GetMapping("/game/stats/{userId}/{gameType}")
    public Result<Map<String, Object>> getGameStats(@PathVariable Long userId, @PathVariable String gameType) {
        try {
            GameSession.GameStats stats = gameSessionService.getUserGameStats(userId, gameType);

            Map<String, Object> result = new HashMap<>();
            result.put("totalQuestions", stats.getTotalQuestions());
            result.put("correctAnswers", stats.getCorrectAnswers());
            result.put("accuracyRate", String.format("%.1f%%", stats.getAccuracyRate()));
            result.put("averageResponseTime", String.format("%.1f秒", stats.getAverageResponseTime() / 1000.0));

            return Result.success(result);
        } catch (Exception e) {
            log.error("获取游戏统计异常: {}", e.getMessage(), e);
            return Result.error("获取统计失败: " + e.getMessage());
        }
    }

    /**
     * 构建游戏会话信息
     */
    private Map<String, Object> buildGameSessionInfo(GameSession gameSession) {
        Map<String, Object> sessionInfo = new HashMap<>();
        sessionInfo.put("sessionId", gameSession.getSessionId());
        sessionInfo.put("gameType", gameSession.getGameType());
        sessionInfo.put("gameState", gameSession.getGameState().name());
        sessionInfo.put("score", gameSession.getScore());
        sessionInfo.put("winStreak", gameSession.getWinStreak());
        sessionInfo.put("level", gameSession.getLevel());
        sessionInfo.put("currentChallenge", gameSession.getCurrentChallenge());

        // 游戏配置信息
        Map<String, Object> config = new HashMap<>();
        config.put("maxQuestions", gameSession.getGameConfig().getMaxQuestions());
        config.put("timeLimit", gameSession.getGameConfig().getTimeLimit());
        config.put("difficulty", gameSession.getGameConfig().getDifficulty());
        config.put("enableHints", gameSession.getGameConfig().isEnableHints());
        config.put("hintsRemaining", gameSession.getGameConfig().getHintsRemaining());
        config.put("pointsPerCorrect", gameSession.getGameConfig().getPointsPerCorrect());
        config.put("bonusMultiplier", gameSession.getGameConfig().getBonusMultiplier());
        sessionInfo.put("config", config);

        // 游戏统计
        GameSession.GameStats stats = gameSession.getGameStats();
        Map<String, Object> statsInfo = new HashMap<>();
        statsInfo.put("totalQuestions", stats.getTotalQuestions());
        statsInfo.put("correctAnswers", stats.getCorrectAnswers());
        statsInfo.put("accuracyRate", stats.getAccuracyRate());
        statsInfo.put("averageResponseTime", stats.getAverageResponseTime());
        sessionInfo.put("stats", statsInfo);

        return sessionInfo;
    }

}
